<template>
  <div>

    <div class="card" style="margin-bottom: 10px;">
      <el-input v-model="username"  prefix-icon="Search" style="width: 300px; margin-right: 10px" placeholder="请输入用户名查询"></el-input>
      <el-input v-model="name" prefix-icon="Search" style="width: 300px; margin-right: 10px" placeholder="请输入名称查询"></el-input>
      <el-button type="primary" @click="load(1)">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 10px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="addUserForm" >新增</el-button>
        <el-button type="danger" @click="delBatch" >批量删除</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" stripe :header-cell-style="{backgroundColor: 'aliceblue', color: '#666'}" @selection-change="handleSelectionChange">   <!--:data="data.tableData"-->
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="name" label="姓名"/>
        <el-table-column prop="avatar" label="头像">
         <template v-slot="scope">
           <img :src="scope.row.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="" style="width: 50px; height: 50px; border-radius: 50%">
         </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column prop="address" label="地址"/>
        <el-table-column label="操作" width="180">
          <template v-slot="scope">
            <el-button type="primary" @click="updateUserForm(scope.row)">编辑</el-button>
            <el-button type="danger"  @click="deleteUser(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin: 10px 0">
      <div class="example-pagination-block">
        <el-pagination
            @current-change="handleCurrentChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, prev, pager, next"
            :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
        v-model="userFormVis"
        title="新增用户"
        width="40%"
    >
      <el-form :model="userForm" label-width="80px" style="padding-right: 20px" :rules="rules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" auto-complete="off" placeholder="请输入用户名" ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" auto-complete="off" placeholder="请输入密码" ></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio v-model="userForm.sex" label="男">男</el-radio>
          <el-radio v-model="userForm.sex" label="女">女</el-radio>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone"  placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"  placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input type="textarea" v-model="userForm.address"  placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9090/file/upload"
              :headers="{token: userForm.token}"
              list-type="picture"
              :on-success="handleAvatarSuccess"
          >
            <el-button type="primary">上传头像</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" style="text-align: right;"  >
        <el-button @click="userFormVis = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/utils/request";
import {handleCurrentChange} from "element-plus/es/components/tree/src/model/util";
import {ElMessage, ElMessageBox} from "element-plus";

export default {
  name: "User",
  data() {
    return {
      userFormVis: false,
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      name: '',
      username: '',
      userForm: {},
      ids: [],
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.load()
  },
  methods: {

    reset() {     //重置查询条件
      this.name = ''
      this.username = ''
      this.load()
    },
    load(pageNum) {   //分页查询
      if (pageNum) {
        this.pageNum = pageNum
      }
      request.get('/user/selectByPage' , {
        params: {pageNum: this.pageNum, pageSize: this.pageSize,name:this.name,username:this.username}
      }).then(res =>{
        this.tableData = res.data.list
        this.total = res.data.total
        console.log("用户数据:", this.tableData);
      }).catch(err => {
        console.error("获取用户数据失败:", err);
      });
    },
    handleCurrentChange(pageNum){
      this.load(pageNum);
    },
    save() {
      // 新增或更新逻辑
      this.$refs.userForm.validate(async valid => {
        if (valid) {
          request({
            url: this.userForm.id ? '/user/update' : '/user/add',
            method: this.userForm.id ? 'put' : 'post',
            data: this.userForm,
          }).then(response => {
            if (response.code === 1) {
              ElMessage.success('保存成功');
              this.userFormVis = false;
              this.load();
            } else {
              ElMessage.error(response.msg);
            }
          })
        }
      });
    },
    deleteUser(row) {
      // 删除逻辑
      console.log("删除用户:", row.id);
      ElMessageBox.confirm(
          `是否确定删除用户 ${row.username}?`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
       request.delete(`/user/delete/${row.id}`).then(response => {
         if (response.code === 1) {
           ElMessage.success('删除成功');
           this.load()
         } else {
           ElMessage.error(response.msg);
         }
       });
      }).catch(() => {})
    },
    updateUserForm(row){     //编辑数据表单
      this.userForm = JSON.parse(JSON.stringify(row))   //给form对象赋值  深拷贝
      this.userFormVis = true  //显示表单
      this.$nextTick(() => {
        this.$refs.upload.clearFiles(); // 清除上传文件
      });
    },
    addUserForm(){     //新增数据表单
      this.userForm = {}
      this.userFormVis = true  //显示表单
      this.$nextTick(() => {
        this.$refs.upload.clearFiles(); // 清除上传文件
      });
    },
    handleAvatarSuccess(response, file, fileList){
      this.userForm.avatar = response.data
    },
    handleSelectionChange(rows){
     this.ids = rows.map(item => item.id)
    },
    delBatch(){
      if (this.ids.length === 0){
        ElMessage.error('请选择要删除的用户');
        return;
      }
      ElMessageBox.confirm(
          `是否确定删除选中的 ${this.ids.length} 个用户?`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        request.delete(`/user/delete/batch`,{data:this.ids}).then(response =>{
          if (response.code === 1){
            ElMessage.success('删除成功');
            this.load();
          }else {
            ElMessage.error(response.msg);
          }
        })
      })
    }

  }
}
</script>

<style scoped>
.example-pagination-block + .example-pagination-block {
  margin-top: 10px;
}
</style>
